package netty.io.demo.Netty.http;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.HttpServerExpectContinueHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * selector 模型 主从线程
 */
public class HttpHelloWorldServer {
  public static void main(String[] args) throws InterruptedException {
    // boss group 主处理
    NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
    // work group work处理
    NioEventLoopGroup workGroup = new NioEventLoopGroup();
    
    try {
      // 服务 bootstrap
      ServerBootstrap b = new ServerBootstrap();
      b.group(bossGroup, workGroup)
          // 设置 socket channel 通道
          .channel(NioServerSocketChannel.class)
          // logging 事件
          .handler(new LoggingHandler(LogLevel.INFO))
          // 添加事件
          .childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
              ChannelPipeline p = socketChannel.pipeline();
              
              // 从 这里 处理 http 编解码
              // netty针对http编解码的处理类
              p.addLast(new HttpServerCodec());
              // netty针对http编解码的处理类
              p.addLast(new HttpServerExpectContinueHandler());
              // 设置 自定义的 server handler
              p.addLast(new HttpHelloWorldServerHandler());
            }
          });
      
      // 以阻塞的方式 绑定端口
      ChannelFuture cf = b.bind(10011).sync();
      // 阻塞 等待服务通道关闭
      cf.channel().closeFuture().sync();
    } finally {
      bossGroup.shutdownGracefully().sync();
      workGroup.shutdownGracefully().sync();
    }
  }
}
